<template>
  <div>
    <div class="category_title">
      <div><span class="shutiao"></span><span>新增就诊医院信息</span></div>
      <el-button type="primary" @click="dialogNewFormVisible = true">添加</el-button>
    </div>

    <!-- 医院信息 start -->
    <div v-for="hospital in hospitals" :key="hospital.modCode">
      <div class="hospital_title">
        <span>{{ hospital.patMedTime | format_patMedTime }}</span>
        <h3>{{ hospital.hosName }}</h3>
      </div>

      <el-collapse v-model="active_hospital_collapse_item_name" accordion>
        <!-- 模块 start -->
        <el-collapse-item
          class="collapse-item hospital-item"
          v-for="(collapse_item, collapse_item_index) in hospital.followYzyMemberMedicalInfoList"
          :key="collapse_item_index"
        >
          <template slot="title">
            {{ collapse_item.modName }}
          </template>

          <!-- 图片区 start -->
          <div class="source">
            <div>
              <ul class="el-upload-list el-upload-list--picture-card">
                <li
                  class="el-upload-list__item"
                  v-for="(item,index) in collapse_item.followYzyMemberMedicalInfoImgFiles"
                  :key="index"
                >
                  <img
                    :src="
                      baseURL +
                        '/api-fol/followYzyFileStorages/followYzyFileStorage/img?fileId=' +
                        item.fileId
                    "
                    alt=""
                    class="el-upload-list__item-thumbnail"
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="
                        module_preview(
                          baseURL +
                            '/api-fol/followYzyFileStorages/followYzyFileStorage/img?fileId=' +
                            item.fileId
                        )
                      "
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="removeHospitalfile(index, item)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </li>
              </ul>
              <div
                class="el-upload el-upload--picture-card"
                @change="onHospitalUpload($event, collapse_item)"
              >
                <i class="el-icon-plus"></i>
                <input
                  type="file"
                  name="files"
                  class="upload_input"
                  accept="image/*"
                  value="点击上传"
                />
              </div>
            </div>
          </div>
          <!-- 图片区 end -->
        </el-collapse-item>
        <!-- 模块 end -->
      </el-collapse>
    </div>
    <!-- 医院信息 end -->

    <!-- 弹窗 医院信息 预览窗口 start -->
    <el-dialog :visible.sync="dialogPreviewHostipalImageVisible">
      <img width="100%" :src="dialogPreviewHostipalImageUrl" alt="" />
    </el-dialog>
    <!-- 弹窗 医院信息 预览窗口 end-->

    <!-- 弹窗 新增 start -->
    <el-dialog
      title="新增就诊信息"
      :visible.sync="dialogNewFormVisible"
      width="80%"
      @closed="reset_formNewHospital('newForm')"
    >
      <el-form
        ref="newForm"
        :inline="true"
        :model="formNewHospital"
        :rules="formNewHospital_rules"
      >
        <el-form-item label="就诊医院名称" prop="hospitalName">
          <el-input
            v-model="formNewHospital.hospitalName"
            placeholder="就诊医院名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="模块" prop="moduleName">
          <el-select
            v-model="formNewHospital.moduleName"
            placeholder="选择模块"
          >
            <el-option
              v-for="item in modules"
              :key="item.code"
              :label="item.name"
              :value="item.name + '@' + item.code"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="时间" prop="patMedTime">
          <el-date-picker
            v-model="formNewHospital.patMedTime"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button @click="onAddModule()">新增</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>

      <el-collapse v-model="active_collapse_item_name" accordion>
        <el-collapse-item
          v-for="(item, index) in formNewHospital.moduleNames"
          :key="index"
          :name="'n' + index"
          class="collapse-item"
        >
          <template slot="title">
            {{ item.split("@")[0]
            }}<el-button
              type="text"
              class="remove"
              icon="el-icon-delete"
              @click="removeMoudle($event, index, item)"
            ></el-button>
          </template>

          <!-- 图片区 start -->
          <div class="source">
            <div>
              <ul class="el-upload-list el-upload-list--picture-card">
                <li
                  class="el-upload-list__item"
                  v-for="(pic, i) in previews[index]"
                  :key="i"
                >
                  <img
                    :src="pic.src"
                    alt=""
                    class="el-upload-list__item-thumbnail"
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="item_preview(pic.src)"
                      ><i class="el-icon-zoom-in"></i
                    ></span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="removeFile(pic.feedback, index, i, item)"
                      ><i class="el-icon-delete"></i
                    ></span>
                  </span>
                </li>
              </ul>
              <div class="el-upload el-upload--picture-card">
                <i class="el-icon-plus"></i>
                <input
                  :ref="'file' + index"
                  type="file"
                  name="files"
                  class="upload_input"
                  accept="image/*"
                  value="点击上传"
                  @change="onUpload($event, index, item)"
                />
              </div>
            </div>
          </div>
          <!-- 图片区 end -->
        </el-collapse-item>
      </el-collapse>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogNewFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onAddNewHospital('newForm')">保存</el-button
        >
      </div>

      <!-- 弹窗内 预览弹窗 start  -->
      <el-dialog :visible.sync="dialogPreviewImageVisible" append-to-body>
        <img width="100%" :src="dialogPreviewImageUrl" alt="" />
      </el-dialog>
      <!-- 弹窗内 预览弹窗 end  -->
    </el-dialog>
    <!-- 弹窗 新增 end -->
  </div>
</template>

<script>
let _arr = [];
import {
  baseURL,
  getModules,
  upload,
  addNewHospital,
  removeFiles,
  removeNewFiles,
  getInfos,
  editHospital
} from "@/api/follow-up/the-hospital-information.js";
export default {
  props: ["patId"],
  data() {
    return {
      baseURL: baseURL,
      dialogPreviewImageUrl: "", //新增 预览图片窗口
      dialogPreviewImageVisible: false,

      dialogPreviewHostipalImageUrl: "", //就诊 预览图片窗口
      dialogPreviewHostipalImageVisible: false,

      dialogNewFormVisible: false, //新增 窗口状态
      active_collapse_item_name: "", //新增 当前展开面板项

      active_hospital_collapse_item_name: "", //就诊 当前展开面板项

      previews: [], //新增 图片预览集合
      previewsObj: {},
      newFormObj: {},
      formNewHospital: {
        hospitalName: "", //就诊医院名称
        moduleName: "", //模块
        patMedTime:'',//日期时间
        moduleNames: [] //已选模块名集合 modName@modCode
      },
      formNewHospital_rules: {
        hospitalName: [{ required: true, message: "请输入", trigger: "blur" }],
        moduleName: [{ required: true, message: "请输入", trigger: "change" }],
        patMedTime:[{ required: true, message: '请输入', trigger: 'blur' }]
      },
      modules: [], //模块集合

      infos: [], //就诊信息列表
      hospitals: [], //就诊医院列表
      files: []
    };
  },
  computed: {},
  filters:{
    format_patMedTime(datetime){
      let _datetime = ''
      if(datetime){
        _datetime = datetime[0]+'年'+datetime[1]+'月'+datetime[2]+'日'
      }

      return _datetime
    }
  },
  methods: {
    test() {
      this.getHospitals();
      
    },
    /**
     * 获取 patientId
     */
    getPatientId() {
      let _id = this.$route.query.patId || this.patId;
      return _id;
    },
    /** 获取医院集合 */
    getHospitals() {
      let memId = this.getPatientId();

      let b = {
        memId: memId
      };

      getInfos(b).then(res => {
        let result = res.data;
        this.infos = result;
        let obj = {};
        this.hospitals = result;
        // this.hospitals = result.reduce((current, next) => {
        //   obj[next.hosName]? "": (obj[next.hosName] = true && current.push({hosName:next.hosName,patMedTime:next.patMedTime}));
        //   return current;
        // }, []);
      });
    },
    /**
     * previewsObj 初始化属情且设为数组
     */
    previewsObj_init() {
      let moduleNames = this.formNewHospital.moduleNames;
      moduleNames.forEach(item => {
        if (this.previewsObj["a" + item.split("@")[1]] === undefined) {
          this.previewsObj["a" + item.split("@")[1]] = [];
        }
      });
    },
    /**
     * 预览图片 新增就诊信息
     */
    item_preview(img) {
      this.dialogPreviewImageUrl = img;
      this.dialogPreviewImageVisible = true;
    },
    /**
     * 预览图片 就诊
     */
    module_preview(img) {
      this.dialogPreviewHostipalImageUrl = img;
      this.dialogPreviewHostipalImageVisible = true;
    },
    /**
     * 重置 新增就诊信息表单
     */
    reset_formNewHospital(formName) {
      this.formNewHospital = {
        hospitalName: "",
        moduleName: "",
        moduleNames: []
      };
      this.previews = [];
      this.previewsObj = {};
      this.newFormObj = {};
      this.newFormData = [];
      this.$refs[formName].resetFields();
    },
    /**
     * 新增 模块
     */
    onAddModule() {
      let that = this;
      let item = this.formNewHospital;

      if (item.moduleName === "") {
        this.$message.error("请先选择模块");
        return false;
      }

      if (item.moduleNames.includes(item.moduleName)) {
        this.$message.error("已选择该模块，请重新选择");
      } else {
        item.moduleNames.push(item.moduleName);
        that.previewsObj_init();
      }
    },
    /**
     * 上传 图片集合 新增
     */
    async onUpload(e, index, module) {
      let that = this;
      let files = e.target.files;
      let _moduleName = "a" + module.split("@")[1];
      let _arr = this.previewsObj[_moduleName];
      let _newFormObj = this.newFormObj[_moduleName];

      let formdata = new FormData();

      for (let file of files) {
        formdata.set("files", file);
        _arr.push({
          name: file.name,
          src: URL.createObjectURL(file),
          feedback: that.handleFile(formdata)
        });
      }

      this.$set(this.previews, index, _arr); //预览

      if (!_newFormObj) {
        _newFormObj = {};
        _newFormObj.followYzyMemberMedicalInfoImgFiles = [];
        _newFormObj.memId = that.getPatientId(); //患者ID
        _newFormObj.modCode = module.split("@")[1]; //模块ID
        _newFormObj.modName = module.split("@")[0]; //模块名称
      }

      await _arr.forEach(item1 => {
        item1.feedback.then(res => {
          if (
            !_newFormObj.followYzyMemberMedicalInfoImgFiles.includes(res.fileId)
          ) {
            _newFormObj.followYzyMemberMedicalInfoImgFiles.push(res.fileId);
          }
        });
      });

      this.$set(this.newFormObj, _moduleName, _newFormObj);
      this.$refs["file" + index].value = null;
    },
    /**
     * 后台处理单个图片
     */
    async handleFile(formdata) {
      let result = "";
      let fileId = "";
      let code = 0;

      await upload(formdata)
        .then(res => {
          result = res.data[0];
          fileId = result.fileId;
          code = 1;
        })
        .catch(err => {
          code = 2;
        });

      return {
        code: code,
        fileId: fileId
      };
    },

    /**
     * 上传 图片集合 就诊
     */
    onHospitalUpload(e, item) {
      let that = this;
      let files = e.target.files;

      let formdata = new FormData();
      let oldfiles = [];
      let newfiles = [];
      let _newfiles = [];
      let _followYzyMemberMedicalInfoImgFiles = [];
      let infos = this.infos;

      oldfiles = item.followYzyMemberMedicalInfoImgFiles.map(
        (val, index, arr) => {
          return { fileId: val.fileId };
        }
      );

      for (let file of files) {
        formdata.set("files", file);
        newfiles.push({
          name: file.name,
          src: URL.createObjectURL(file),
          feedback: that.handleFile(formdata)
        });
      }

      newfiles.forEach((item1, index) => {
        item1.feedback.then(res => {
          _newfiles.push({ fileId: res.fileId });

          if (_newfiles.length <= 0) {
            return;
          }

          _followYzyMemberMedicalInfoImgFiles = [...oldfiles, ..._newfiles];

          infos.forEach((info, i) => {
            if (info.patMedInfoId == item.patMedInfoId)
              infos[
                i
              ].followYzyMemberMedicalInfoImgFiles = _followYzyMemberMedicalInfoImgFiles;
          });

          let b = {
            memberMedicalInfoForInsertMedInfoVOS: infos,
            memId: item.memId //患者ID
          };

          editHospital(b).then(res => {
            this.$message({
              message: "操作成功",
              type: "success"
            });
          });
        });
      });
    },

    /**
     * 删除图片 新增弹窗
     * @ index 所在模块排序
     * @ i     当前图集中的排序
     */
    removeFile(feedback, index, i, module) {
      feedback.then(res1 => {
        let _moduleName = "a" + module.split("@")[1];
        let _arr = this.previewsObj[_moduleName];
        let files = this.newFormObj[_moduleName]
          .followYzyMemberMedicalInfoImgFiles;
        let _files = [];

        /** 前端删除 */
        _arr = _arr.filter((item, k) => k !== i);
        _files = files.filter(fileid => fileid !== res1.fileId);
        this.newFormObj[_moduleName].followYzyMemberMedicalInfoImgFiles = [];
        this.newFormObj[_moduleName].followYzyMemberMedicalInfoImgFiles.push(
          _files
        );

        this.$set(this.previewsObj, _moduleName, _arr);
        this.$set(this.previews, index, _arr); //预览

        /** 请求后端删除 */
        let fileId = res1.fileId;
        let b = [fileId];
        removeFiles(b).then(res2 => {
          this.$message({
            message: "删除成功",
            type: "success"
          });
        });
      });
    },
    /**
     * 删除图片 就诊
     */
    removeHospitalfile(index, file) {
      let b = [file];

      removeNewFiles(b).then(res => {
        this.$message({
          message: "删除成功",
          type: "success"
        });

        this.getHospitals();
      });
    },
    /**
     * 提交 新增就诊信息表单
     */
    onAddNewHospital(formName) {
      let that = this
      let _state = true
      let _newFormData = JSON.parse(JSON.stringify(this.newFormObj))
      _newFormData = Object.values(_newFormData)

      this.$refs[formName].validate(valid => {
        if (valid) {
          if (_newFormData.length === 0) {
            this.$message.error('请新增模块并上传图片')
            return false
          }

          _newFormData.forEach(item => {
            item.hosName = that.formNewHospital.hospitalName
            item.patMedTime = this.formNewHospital.patMedTime
            if (item.followYzyMemberMedicalInfoImgFiles.length <= 0) {
              _state = false
              return
            }
          })

          if (!_state) {
            this.$message({
              showClose: true,
              message: '图片上传中，请稍等',
              type: 'warning'
            })
            return false
          }

          _newFormData.forEach((item1, i) => {
            _newFormData[i].followYzyMemberMedicalInfoImgFiles = item1.followYzyMemberMedicalInfoImgFiles.map(
              item2 => {
                let json = {}
                json.fileId = item2
                return json
              }
            )
          })

          let b = _newFormData


           addNewHospital(b).then(res => {
            this.$message({
              message: '操作成功',
              type: 'success'
            })

            this.getHospitals()
          })

          that.dialogNewFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /**
     * 获取 模块集合
     */
    getModules() {
      let that = this;
      let b = {
        rangeCode: "module_type"
      };

      getModules(b).then(res => {
        let result = res.data;
        that.modules = result;
      });
    },
    getAllItems() {
      this.getModules();
      this.getHospitals();
    },
    removeMoudle(e, index, module) {
      e.stopPropagation();

      /** 前端删除 */
      let _moduleNames = this.formNewHospital.moduleNames;
      _moduleNames = _moduleNames.filter((item, i) => i !== index);
      let _modCode = module.split("@")[1];
      let _modName = "a" + _modCode; //模块名
      let _newFormData = JSON.parse(JSON.stringify(this.newFormObj));
      let _newFormData_cur = _newFormData[_modName];

      this.$set(this.formNewHospital, "moduleNames", _moduleNames);
      this.previews.splice(index, 1);
      this.previewsObj[_modName] = [];

      /** 请求后端删除 */

      let b = _newFormData_cur.followYzyMemberMedicalInfoImgFiles;

      removeFiles(b).then(res => {
        this.$message({
          message: "删除成功",
          type: "success"
        });

        /** 前端移除当前模块数据 */
        delete _newFormData[_modName];
        this.newFormObj = _newFormData;
      });
    }
  },
  mounted: function() {
    this.getAllItems();
  }
};
</script>

<style lang="scss" scoped>
.hospital_title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #4380ea;
}
.category_title {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .shutiao {
    display: inline-block;
    width: 5px;
    height: 20px;
    border-radius: 28%;
    background-color: #4380ea;
    vertical-align: middle;
    margin-right: 6px;
  }
}
.el-collapse {
  position: relative;
  .collapse-item /deep/ {
    .el-collapse-item__header {
      padding-right: 17px;
    }
  }
  .collapse-item.hospital-item /deep/ {
    .el-collapse-item__header {
      padding-right: 0;
    }
  }
}
.remove {
  position: absolute;
  right: 0;
}
i.el-collapse-item__arrow {
  display: block;
  margin-right: 1000px;
}

.el-upload--picture-card {
  position: relative;
  overflow: hidden;
  .upload_input {
    display: block !important;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    opacity: 0;
    cursor: pointer;
  }
}
.dialog-footer{
  text-align:center
}
</style>